package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        Map map = new HashMap();

        //1.检验用户是否登录
        if (StringUtils.isNoneBlank(dto.getPhone()) && StringUtils.isNoneBlank(dto.getPassword())) {
            //1.1根据手机号去查ApUse表
            ApUser apuser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //1.2不存在则返回错误信息
            if (apuser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //存在则校验密码是否与数据库一样
            //1.3存在则开始校验密码
            String password = dto.getPassword();
            String salt = apuser.getSalt();
            //对明文密码进行加密
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //1.3.2错误则返回错误信息
            if (!pwd.equals(apuser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            }
            String token = AppJwtUtil.getToken(apuser.getId().longValue());
            //1.3.1密码正确返回taoken
            //封装数据
            apuser.setSalt(" ");
            apuser.setPassword(" ");
            map.put("token", token);
            map.put("user", apuser);
        } else {
            //不存在 则游客登录
            String token = AppJwtUtil.getToken(0L);
            map.put("token", token);
            //直接返回taoken
        }
        //返回数据
        return ResponseResult.okResult(map);
    }
}
